<template>
    <div class="pannel-account">
        <el-form :rules="rules" ref="formRef" :model="account" label-width="50px" :size="'default'"
            style="max-width: 460px">
            <el-form-item label="帐号" prop="name">
                <el-input v-model="account.name" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="account.password" show-password />
            </el-form-item>

        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { ElForm, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { accountLoginRequest } from '@/service/login/login'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache';

const ruleFormRef = ref<FormInstance>()
const account = reactive<IAccount>({
    name: localCache.getCache('name') ?? '',
    password: localCache.getCache('password') ?? ''
})


const rules: FormRules = {
    name: [
        { required: true, message: '必须输入账号', trigger: 'blur' },
        { min: 3, max: 6, message: '必须是3-6位', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '必须输入密码', trigger: 'blur' },
        { min: 3, max: 6, message: '必须是3-6位', trigger: 'blur' }
    ]
}

// 执行账号登录逻辑
const formRef = ref<InstanceType<typeof ElForm>>()

const loginStore = useLoginStore()
function loginAction(isRememberPwd: boolean) {
    formRef.value?.validate((valid) => {
        if (valid) {
            const name = account.name
            const password = account.password

            // 向服务器发送请求
            loginStore.loginAccountAction({ name, password }).then((res) => {
                if (isRememberPwd) {
                    localCache.setCache("name", name)
                    localCache.setCache('password', password)
                }
            })

        } else {
            ElMessage.error('Oops, this is a error message.')
        }
    })
}
defineExpose({
    loginAction
})





</script>

<style lang="less" scoped>
.pannel-account {
    color: red;
}
</style>